const mongoose = require('mongoose');
const bcrypt = require('bcrypt')
const joi = require('joi')
const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 20
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },

    role: {
        type: String,
        required: true
    },
    // 0表示启用状态
    state: {
        type: String,
        default: 0
    }
});
const User = mongoose.model('User', userSchema)
async function createUser() {
    const salt = await bcrypt.genSalt(10);
    const pass = await bcrypt.hash('123456', salt)

    // const user = await User.create({
    //     username: 'carrie',
    //     email: '6666@qq.com',
    //     password: pass,
    //     role: 'admin',
    //     state: 0
    // })
}
// 验证用户信息
const validateUser = user => {
    const schema = {
        username: joi.string().required().min(2).max(12).error(new Error('用户名不符合验证规则')),
        email: joi.string().email().required().error(new Error('邮箱格式不符合要求')),
        password: joi.string().regex(/^[a-zA-Z0-9]{3,30}$/).required().error(new Error('密码格式不符合要求')),
        role: joi.string().valid('normal', 'admin').required().error(new Error('角色值非法')),
        state: joi.number().valid(0, 1).required().error(new Error('状态值非法'))
    };
    return joi.validate(user, schema)
}

// 将用户集合作为模块成员导出
module.exports = {
    User,
    validateUser
}